//
//  BSBaseThemeViewController.m
//  BaiSi
//
//  Created by Sycamore on 16/5/8.
//  Copyright © 2016年 Sycamore. All rights reserved.
//

#import "BSBaseThemeViewController.h"
#import <AFNetworking/AFNetworking.h>
#import "BSThemeCell.h"
#import "BSThemeItem.h"
#import <MJExtension/MJExtension.h>
#import "BSThemeCellModel.h"
#import <SDImageCache.h>
#import <MJRefresh/MJRefresh.h>
#import "BSEssenceViewController.h"
#import "BSCommentViewController.h"


@interface BSBaseThemeViewController ()
@property (nonatomic,strong) NSMutableArray *cellModels;
@property (nonatomic,strong) NSNumber *maxtime;
@property (nonatomic,weak) AFHTTPSessionManager *mgr;
@property (nonatomic,strong) NSString *list;

@end

static NSString * const ID = @"cell";

@implementation BSBaseThemeViewController

//写在这里仅仅是为了消除警告
- (ThemeType)type
{
    return ThemeTypeAll;
}

- (void)loadData
{
    //刷新数据
    [self.tableView.mj_header beginRefreshing];
}

//精华控制器和新帖控制器需要传入不同的参数
- (NSString *)list
{
    if ([self.parentViewController isKindOfClass:[BSEssenceViewController class]]) {
        return @"list";
    }
    return @"newlist";
}

- (void)loadView
{
    self.tableView = [[UITableView alloc]initWithFrame:BSScreenBounds];
}

- (AFHTTPSessionManager *)mgr
{
    if (!_mgr) {
        _mgr = [AFHTTPSessionManager manager];
    }
    return _mgr;
}

- (NSMutableArray *)cellModels
{
    if (!_cellModels) {
        _cellModels = [NSMutableArray array];
    }
    return _cellModels;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.backgroundColor = BSTintColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tableView registerClass:[BSThemeCell class] forCellReuseIdentifier:ID];
    
    //发送网络请求，获取数据
//    [self loadNewData];
    
    //添加下拉刷新控件
    [self setupHeaderRefreshView];
    
    //添加上拉刷新控件
    [self setupFooterRefreshView];
    
    //设置这个后，tabelView会自己滚动，那么就会调用scrollViewDidScroll这个方法
    self.tableView.contentInset = UIEdgeInsetsMake(64 + 35 , 0, 49, 0);
    
    //一加载就刷新一次
    [self.tableView.mj_header beginRefreshing];
    
    
    //监听刷新的通知
    [[NSNotificationCenter defaultCenter]addObserverForName:BSTableRefreshNote object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        //一监听到通知就会调用此方法(用window和superView都可以进行判断->superView会有一个bug，让精华和新帖中的正在显示的viw同时刷新数据)
        if (self.view.window) {
            [self loadData];
        }
        
    }];
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:BSTableRefreshNote object:nil];
}

//添加上拉刷新控件
- (void)setupFooterRefreshView
{
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.automaticallyHidden = YES;
    self.tableView.mj_footer = footer;
    
}

- (void)setupHeaderRefreshView
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    header.automaticallyChangeAlpha = YES;
    self.tableView.mj_header = header;
    
}

#pragma mark  处理网络请求
- (void)loadNewData
{
    
    [self.mgr.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    NSDictionary *params = @{
                             @"a" : self.list,
                             @"c" : @"data",
                             @"type" : @(self.type)
                             };
    [self.mgr GET:BSBaseURL parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        //获取maxtime
        _maxtime = responseObject[@"info"][@"maxtime"];
        
        //完成上拉刷新
        [self.tableView.mj_header endRefreshing];
        
        
        NSArray *items = [BSThemeItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        //将普通模型数组转成视图模型数组
        for (BSThemeItem *item in items) {
            BSThemeCellModel *cellModel = [[BSThemeCellModel alloc]init];
            
            cellModel.item = item;
            [_cellModels addObject:cellModel];
        }
        
        //计算cell的高度
        
        [self.tableView reloadData];
        
        
        
    } failure:nil];
}

- (void)loadMoreData
{
    
    [self.mgr.tasks makeObjectsPerformSelector:@selector(cancel)];
    NSDictionary *params = @{
                             @"a" : self.list,
                             @"c" : @"data",
                             @"type" : @(self.type),
                             @"maxtime" : _maxtime
                             };
    [self.mgr GET:BSBaseURL parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        //获取maxtime
        _maxtime = responseObject[@"info"][@"maxtime"];
        //记住，每次完成刷新后要调用此方法
        [self.tableView.mj_footer endRefreshing];
        
        NSArray *items = [BSThemeItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        [responseObject writeToFile:@"/Users/Sycamore/Desktop/BaiSi.plist" atomically:YES];
        
        //将普通模型数组转成视图模型数组
        for (BSThemeItem *item in items) {
            BSThemeCellModel *cellModel = [[BSThemeCellModel alloc]init];
            
            cellModel.item = item;
            [_cellModels addObject:cellModel];
        }
        //计算cell的高度,这里写就不好了，可以弄一个视图模型，把计算放进视图模型里面去计算
        
        [self.tableView reloadData];
    } failure:nil];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cellModels.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BSThemeCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    
    [[SDImageCache sharedImageCache]clearMemory];
    cell.cellModel = _cellModels[indexPath.row];
    return cell;
}

//计算cell的高度，考虑到性能的问题，不应该在数据源方法里面计算，因为调用频繁，可以考虑在收到网络数据后就开始计算
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [_cellModels[indexPath.row] cellHeight];
}

//cell的选中，跳转到评论控制器里面去
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BSCommentViewController *comment = [[BSCommentViewController alloc]init];
    BSThemeCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    //传模型比传cell好，cell传过去之后，这边的容易发生改变，穿模型过去，那一边再根据视图模型重新创建一个cell

    comment.cellModel = cell.cellModel;

    [self.navigationController pushViewController:comment animated:YES];
}
@end
